%% Copyright (C) 2007 Vijay Gajula <gajulak@gmail.com>.
%% All rights reserved.
%%
%% Redistribution and use in source and binary forms, with or without
%% modification, are permitted provided that the following conditions
%% are met:
%%
%% 1. Redistributions of source code must retain the above copyright
%%    notice, this list of conditions and the following disclaimer.
%% 2. Redistributions in binary form must reproduce the above
%%    copyright notice, this list of conditions and the following
%%    disclaimer in the documentation and/or other materials provided
%%    with the distribution.
%%
%% THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
%% OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
%% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%% ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
%% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
%% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
%% GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
%% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
%% WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
%% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
%% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-module(mod_system).
-vsn(1.0).
-author('gajulak@gmail.com').
-export([process_get/1,sys_info/1]).

-include("xmerl.hrl").

process_get(E) ->
	system_config(E).

system_config([#xmlElement{name = all}=E|T]) 
   when record(E, xmlElement) ->
	sys_info(all);
	
system_config([H|T]) -> system_config(T);
system_config([]) -> ok.

sys_info(all) ->
	HostName = os:cmd("/bin/hostname -f"),
	MemStr = os:cmd("/usr/bin/free -m"),
	{ok, Host} = regexp:split(HostName, "\n"),
	{ok, MemList} = regexp:split(MemStr, "\n"),
	[_H1, PhyMem, _H2, SwapMem | T] = MemList,
	X1 = generate_xml(PhyMem, 'physical-memory'),
	X2 = generate_xml(SwapMem, 'swap-memory'),

	Xml = io_lib:format(" 
			<system>
			    <hostname>~s</hostname>
			     ~s
			     ~s
			</system>", 
			[Host, X1, X2]),
        %% io:format("xml : ~s~n",[Xml]),
	%% io:format("~s", [lists:flatten(Xml)]),
	{ok, Xml}.

generate_xml(Mem, Tag) ->
     Str = 
	case regexp:split(Mem, " ") of
	   {ok, [_MemText, Total, Used, Free | _T]} ->
	   		io_lib:format("
				<~s>
				   <total>~s MBytes</total>
				   <used>~s MBytes</used>
				   <free>~s MBytes</free>
				</~s>", 
				[Tag, Total, Used, Free, Tag]);
		 _ -> []
	end.
